/**
 * Created by zhaoxi on 2017/12/4.
 */
import React, {Component} from 'react';


class BaseAsyncComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            component: null,
        };
    }

    render() {
        const C = this.state.component;
        return C
            ? <C {...this.props} />
            : null;
    }
}

export const asyncComponentModels = (injectModel) => (importComponent, importModel) => {
    class AsyncComponent extends BaseAsyncComponent {
        componentDidMount() {
            importModel
                .then(result => {
                    result.forEach((a)=>{
                        injectModel(a.default)
                    });
                    return importComponent();
                })
                .then(result => {
                    this.setState({component: result.default});
                });
        }
    }

    return AsyncComponent;
};

export const asyncComponentModel = (injectModel) => (importComponent, importModel) => {

    class AsyncComponent extends BaseAsyncComponent {
        componentDidMount() {
            importModel()
                .then(result => {
                    injectModel(result.default);
                    return importComponent();
                })
                .then(result => {
                    this.setState({component: result.default});
                });
        }
    }

    return AsyncComponent;
};


export const asyncComponent = (importComponent) => {
    class AsyncComponent extends BaseAsyncComponent {
        componentDidMount() {
            importComponent().then(result => {
                this.setState({component: result.default});
            });
        }
    }

    return AsyncComponent;
};